Page({
    data: {
      categoryId: null,       
      categoryName: '',       
      allRecipes: [],        // 存储所有课程数据
      filteredRecipes: [],   // 搜索过滤后的数据
      displayRecipes: [],    // 当前展示的数据
      searchKeyword: '',      
      isLoading: false,      // 首次加载/重试的全局加载状态
      loadError: false,      // 加载错误状态
      showLoadingMore: false,// 下拉加载时的Vant加载组件
      showEndText: false,    // 到底提示
      currentPage: 1,        // 当前页码
      pageSize: 8            // 每页8条
    },
  
    onLoad(options) {
      console.log('分类详情页接收参数：', options); 
      let categoryId = options.categoryId || options.id; 
      const categoryName = options.categoryName || '';
  
      // 校验分类ID
      if (!categoryId || isNaN(Number(categoryId))) {
        wx.showToast({ title: '分类ID无效', icon: 'none' });
        setTimeout(() => wx.navigateBack(), 1500);
        return;
      }
      categoryId = Number(categoryId);
  
      this.setData({ categoryId, categoryName: categoryName || '菜谱分类' });
      this.fetchCategoryRecipes();
    },
  
    // 监听页面滚动到底部（下拉加载触发）
    onReachBottom() {
      // 搜索中、加载中、无更多数据时不触发
      if (this.data.searchKeyword || this.data.isLoading || this.data.showEndText || this.data.loadError) {
        return;
      }
      this.loadMore();
    },
  
    // 获取分类下所有数据
    fetchCategoryRecipes() {
      // 重置状态，确保首次加载显示大圆圈
      this.setData({ 
        isLoading: true, 
        loadError: false,
        displayRecipes: [],
        showLoadingMore: false,
        showEndText: false
      });
  
      const token = wx.getStorageSync('token') || '';
  
      wx.request({
        url: `http://localhost:8080/course/categories/detail/${this.data.categoryId}`,
        method: 'GET',
        header: {
          'content-type': 'application/json',
          'Authorization': token ? `Bearer ${token}` : '' 
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data.code === 200) {
            const { data } = res.data;
            this.processRecipeData(data);
          } else {
            this.setData({ 
              loadError: true,
              isLoading: false
            });
            wx.showToast({ title: res.data.msg || '数据获取失败', icon: 'none' });
          }
        },
        fail: (err) => {
          console.error('接口请求失败：', err);
          this.setData({ 
            loadError: true,
            isLoading: false
          });
          wx.showToast({ title: '网络异常，请重试', icon: 'none' });
        },
        complete: () => {
          // 仅在请求完成且无错误时关闭加载状态
          if (!this.data.loadError) {
            this.setData({ isLoading: false });
          }
        }
      });
    },
  
    // 处理数据并初始化分页（首次加载前8条）
    processRecipeData(data) {
      if (!data.courses || !Array.isArray(data.courses) || data.courses.length === 0) {
        this.setData({ 
          allRecipes: [], 
          filteredRecipes: [],
          displayRecipes: [],
          showEndText: true,
          isLoading: false
        });
        return;
      }
  
      // 格式化课程数据
      const recipes = data.courses.map(course => ({
        id: course.id,
        title: course.title || '未知课程',
        description: course.description || '',
        score: course.score || 0,
        participantCount: course.participantCount || 0,
        imgUrl: this.getCoverImage(course.images), 
        author: course.users?.nickname || "未知作者",
      }));
  
      // 存储所有数据并加载第一页（前8条）
      this.setData({ 
        allRecipes: recipes, 
        filteredRecipes: recipes
      }, () => {
        this.loadPage(1);
      });
    },
  
    // 加载指定页数据（核心分页逻辑）
    loadPage(pageNum) {
      const startIndex = (pageNum - 1) * this.data.pageSize;
      const endIndex = startIndex + this.data.pageSize;
      const currentData = this.data.filteredRecipes.slice(startIndex, endIndex);
  
      this.setData({
        displayRecipes: [...this.data.displayRecipes, ...currentData],
        currentPage: pageNum
      });
  
      // 判断是否还有更多数据
      const totalCount = this.data.filteredRecipes.length;
      const hasMore = endIndex < totalCount;
      this.setData({
        showEndText: !hasMore,
        showLoadingMore: false // 关闭加载动画
      });
    },
  
    // 下拉加载更多（显示Vant小圆圈）
    loadMore() {
      if (this.data.isLoading) return; // 防止重复加载
  
      this.setData({ 
        isLoading: true,
        showLoadingMore: true // 显示Vant小圆圈
      });
  
      // 模拟网络延迟
      setTimeout(() => {
        const nextPage = this.data.currentPage + 1;
        this.loadPage(nextPage);
        this.setData({ isLoading: false });
      }, 600);
    },
  
    getCoverImage(images) {
        const defaultImg = '/images/default-recipe.png';
        
        // 1. 处理空数组情况
        if (!Array.isArray(images) || images.length === 0) {
          return defaultImg;
        }
      
        // 2. 优先找封面图
        const coverImg = images.find(img => img?.description?.includes('封面图'));
        if (coverImg) {
          // 封面图存在时，处理 URL
          if (coverImg.imgUrl) {
            return coverImg.imgUrl.startsWith('http') 
              ? coverImg.imgUrl 
              : `https://gzq123.oss-cn-beijing.aliyuncs.com/${coverImg.imgUrl}`;
          } else {
            // 封面图有描述但无 URL，兜底到默认图
            return defaultImg;
          }
        }
      
        // 3. 无封面图，取第一张图
        const firstImg = images[0];
        if (firstImg?.imgUrl) {
          return firstImg.imgUrl.startsWith('http') 
            ? firstImg.imgUrl 
            : `https://gzq123.oss-cn-beijing.aliyuncs.com/${firstImg.imgUrl}`;
        } else {
          // 第一张图也无效，兜底到默认图
          return defaultImg;
        }
      },
  
    // 搜索输入处理
    onSearchInput(e) {
      const keyword = e.detail.value.trim();
      this.setData({ searchKeyword: keyword });
  
      // 过滤数据并重置分页
      const filtered = this.data.allRecipes.filter(recipe => 
        recipe.title.toLowerCase().includes(keyword.toLowerCase()) ||
        recipe.description.toLowerCase().includes(keyword.toLowerCase())
      );
  
      this.setData({ 
        filteredRecipes: filtered,
        displayRecipes: [],
        currentPage: 1,
        showEndText: false,
        showLoadingMore: false
      }, () => {
        this.loadPage(1);
      });
    },
  
    // 清空搜索
    clearSearch() {
      this.setData({ 
        searchKeyword: '', 
        filteredRecipes: this.data.allRecipes,
        displayRecipes: [],
        currentPage: 1,
        showEndText: false,
        showLoadingMore: false
      }, () => {
        this.loadPage(1);
      });
    },
  
    // 重新加载数据（错误时调用）
    retryLoad() {
      this.setData({ 
        displayRecipes: [],
        filteredRecipes: [],
        currentPage: 1,
        showEndText: false,
        loadError: false,
        showLoadingMore: false
      }, () => {
        this.fetchCategoryRecipes();
      });
    },
  
    // 跳转到详情页
    goToDetail(e) {
      const recipeId = e.currentTarget.dataset.id;
      if (recipeId) {
        wx.navigateTo({
          url: `/video/pages/recipesDetails/recipesDetails?id=${recipeId}`
        });
      }
    }
  });
  